<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>现代BBS评论系统</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        neutral: '#64748B',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .comment-shadow {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            }
            .reply-line {
                border-left: 2px solid #e2e8f0;
            }
            .btn-hover {
                @apply transition-all duration-200 hover:shadow-lg transform hover:-translate-y-0.5;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-dark">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-comments text-primary text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold text-primary">现代BBS评论系统</h1>
            </div>
            <div class="hidden md:flex items-center space-x-4">
                <button id="themeToggle" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-moon-o text-neutral"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-8 max-w-4xl">
        <!-- 介绍区 -->
        <section class="mb-10 text-center">
            <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold mb-4">欢迎参与讨论</h2>
            <p class="text-neutral max-w-2xl mx-auto">在这里分享你的想法，参与有意义的讨论，尊重他人观点，共同维护友好的交流环境。</p>
        </section>
        
        <!-- 评论表单 -->
        <section class="bg-white rounded-xl p-6 shadow-md mb-10 transform transition-all hover:shadow-lg">
            <h3 class="text-xl font-semibold mb-4 flex items-center text-gray-800 dark:text-gray-200">
                <i class="fa fa-pencil-square-o text-primary mr-2"></i>发表评论
            </h3>
            <form id="commentForm" class="space-y-4">
                <div>
                    <label for="author" class="block text-sm font-medium text-gray-700 mb-1">昵称</label>
                    <input 
                        type="text" 
                        id="author" 
                        required
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all outline-none"
                        placeholder="请输入你的昵称"
                    >
                </div>
                <div>
                    <label for="content" class="block text-sm font-medium text-gray-700 mb-1">评论内容</label>
                    <textarea 
                        id="content" 
                        rows="4" 
                        required
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all outline-none resize-none text-gray-800 dark:text-gray-200"
                        placeholder="分享你的想法..."
                    ></textarea>
                </div>
                <input type="hidden" id="parentId" value="">
                <button 
                    type="submit" 
                    class="bg-primary text-white px-6 py-2.5 rounded-lg font-medium btn-hover flex items-center"
                >
                    <i class="fa fa-paper-plane mr-2"></i>发布评论
                </button>
            </form>
        </section>
        
        <!-- 评论列表 -->
        <section>
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-xl font-semibold flex items-center">
                    <i class="fa fa-comments-o text-primary mr-2"></i>评论列表
                </h3>
                <span id="commentCount" class="bg-gray-100 text-neutral px-3 py-1 rounded-full text-sm"></span>
            </div>
            
            <div id="commentsContainer" class="space-y-6">
                <!-- 评论加载状态 -->
                <div id="loadingIndicator" class="flex justify-center py-10">
                    <div class="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-primary"></div>
                </div>
                
                <!-- 评论将通过JavaScript动态加载 -->
            </div>
            
            <!-- 空状态显示 -->
            <div id="emptyState" class="hidden text-center py-16">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                    <i class="fa fa-comment-o text-2xl text-gray-400"></i>
                </div>
                <h3 class="text-lg font-medium text-gray-900 mb-1">暂无评论</h3>
                <p class="text-neutral">成为第一个发表评论的人吧！</p>
            </div>
        </section>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 mt-16">
        <div class="container mx-auto px-4 py-8 text-center text-neutral">
            <p>© 2025 现代BBS评论系统 | 开新 | 用技术连接思想</p>
        </div>
    </footer>

    <!-- 通知组件 -->
    <div id="notification" class="fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50"></div>

    <script>
        // API基础URL
        const API_BASE_URL = ''; // 空字符串表示与当前页面同域名
        
        // DOM元素
        const commentForm = document.getElementById('commentForm');
        const commentsContainer = document.getElementById('commentsContainer');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const emptyState = document.getElementById('emptyState');
        const commentCount = document.getElementById('commentCount');
        const notification = document.getElementById('notification');
        const themeToggle = document.getElementById('themeToggle');
        
        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadComments();
            setupEventListeners();
        });
        
        // 设置事件监听器
        function setupEventListeners() {
            // 评论表单提交
            commentForm.addEventListener('submit', handleCommentSubmit);
            
            // 主题切换
            themeToggle.addEventListener('click', toggleTheme);
        }
        
        // 加载所有评论
        async function loadComments() {
            try {
                showLoading();
                
                const response = await fetch(`${API_BASE_URL}/comments`);
                if (!response.ok) throw new Error('加载评论失败');
                
                const comments = await response.json();
                renderComments(comments);
                updateCommentCount(comments.length);
                
                hideLoading();
                checkEmptyState(comments.length === 0);
            } catch (error) {
                console.error('加载评论时出错:', error);
                showNotification('加载评论失败，请稍后重试', 'error');
                hideLoading();
                checkEmptyState(true);
            }
        }
        
        // 渲染评论列表
        function renderComments(comments) {
            commentsContainer.innerHTML = '';
            
            // 先显示顶级评论
            const topLevelComments = comments.filter(comment => comment.parent_id === null);
            
            topLevelComments.forEach(comment => {
                const commentElement = createCommentElement(comment, comments);
                commentsContainer.appendChild(commentElement);
            });
        }
        
        // 创建单个评论元素
        function createCommentElement(comment, allComments) {
            const div = document.createElement('div');
            div.className = 'bg-white rounded-xl p-6 comment-shadow transition-all duration-300 hover:shadow-lg';
            div.dataset.id = comment.id;
            
            // 格式化日期
            const formattedDate = new Date(comment.created_at).toLocaleString('zh-CN', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
            
            div.innerHTML = `
                <div class="flex justify-between items-start mb-3">
                    <div class="flex items-center">
                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold mr-3">
                            ${comment.author.charAt(0).toUpperCase()}
                        </div>
                        <div>
                            <h4 class="font-medium text-gray-800 dark:text-gray-200">${escapeHtml(comment.author)}</h4>
                            <p class="text-sm text-neutral">${formattedDate}</p>
                        </div>
                    </div>
                    <div class="flex space-x-2">
                        <button onclick="replyTo(${comment.id}, '${escapeHtml(comment.author)}')" 
                            class="text-neutral hover:text-primary p-1.5 rounded-full hover:bg-gray-100 transition-colors"
                            title="回复">
                            <i class="fa fa-reply"></i>
                        </button>
                        <button onclick="deleteComment(${comment.id})" 
                            class="text-neutral hover:text-red-500 p-1.5 rounded-full hover:bg-gray-100 transition-colors"
                            title="删除">
                            <i class="fa fa-trash-o"></i>
                        </button>
                    </div>
                </div>
                <div class="mb-4">
                    <p class="text-gray-800">${formatCommentContent(escapeHtml(comment.content))}</p>
                </div>
                <div class="replies pl-0 mt-4 space-y-4"></div>
            `;
            
            // 添加回复
            const repliesContainer = div.querySelector('.replies');
            const replies = allComments.filter(c => c.parent_id === comment.id);
            
            replies.forEach(reply => {
                const replyElement = createCommentElement(reply, allComments);
                replyElement.classList.add('reply-line', 'pl-6');
                repliesContainer.appendChild(replyElement);
            });
            
            return div;
        }
        
        // 处理评论提交
        async function handleCommentSubmit(e) {
            e.preventDefault();
            
            const authorInput = document.getElementById('author');
            const contentInput = document.getElementById('content');
            const parentIdInput = document.getElementById('parentId');
            
            const commentData = {
                author: authorInput.value.trim(),
                content: contentInput.value.trim(),
                parent_id: parentIdInput.value ? parseInt(parentIdInput.value) : null
            };
            
            // 简单验证
            if (!commentData.author) {
                return showNotification('请输入昵称', 'warning');
            }
            
            if (!commentData.content) {
                return showNotification('请输入评论内容', 'warning');
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/comments`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(commentData)
                });
                
                if (!response.ok) throw new Error('提交评论失败');
                
                // 重置表单
                commentForm.reset();
                parentIdInput.value = '';
                
                // 重新加载评论
                loadComments();
                
                // 显示成功通知
                showNotification(
                    commentData.parent_id ? '回复成功！' : '评论发表成功！', 
                    'success'
                );
                
            } catch (error) {
                console.error('提交评论时出错:', error);
                showNotification('提交失败，请稍后重试', 'error');
            }
        }
        
        // 回复功能
        function replyTo(commentId, authorName) {
            const parentIdInput = document.getElementById('parentId');
            const contentInput = document.getElementById('content');
            
            parentIdInput.value = commentId;
            contentInput.value = `@${authorName} `;
            contentInput.focus();
            
            // 滚动到评论框
            commentForm.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
        
        // 删除评论
        async function deleteComment(commentId) {
            if (!confirm('确定要删除这条评论吗？删除后将无法恢复。')) {
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/comments/${commentId}`, {
                    method: 'DELETE'
                });
                
                if (!response.ok) throw new Error('删除评论失败');
                
                // 重新加载评论
                loadComments();
                showNotification('评论已删除', 'success');
                
            } catch (error) {
                console.error('删除评论时出错:', error);
                showNotification('删除失败，请稍后重试', 'error');
            }
        }
        
        // 显示通知
        function showNotification(message, type = 'info') {
            // 设置通知类型样式
            let bgColor, textColor, icon;
            
            switch (type) {
                case 'success':
                    bgColor = 'bg-green-500';
                    textColor = 'text-white';
                    icon = 'fa-check-circle';
                    break;
                case 'error':
                    bgColor = 'bg-red-500';
                    textColor = 'text-white';
                    icon = 'fa-exclamation-circle';
                    break;
                case 'warning':
                    bgColor = 'bg-yellow-500';
                    textColor = 'text-white';
                    icon = 'fa-exclamation-triangle';
                    break;
                default:
                    bgColor = 'bg-primary';
                    textColor = 'text-white';
                    icon = 'fa-info-circle';
            }
            
            // 设置通知内容
            notification.className = `fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 flex items-center z-50 ${bgColor} ${textColor}`;
            notification.innerHTML = `<i class="fa ${icon} mr-2"></i> ${message}`;
            
            // 3秒后隐藏通知
            setTimeout(() => {
                notification.className = 'fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50';
            }, 3000);
        }
        
        // 显示加载状态
        function showLoading() {
            loadingIndicator.classList.remove('hidden');
        }
        
        // 隐藏加载状态
        function hideLoading() {
            loadingIndicator.classList.add('hidden');
        }
        
        // 检查空状态
        function checkEmptyState(isEmpty) {
            if (isEmpty) {
                emptyState.classList.remove('hidden');
            } else {
                emptyState.classList.add('hidden');
            }
        }
        
        // 更新评论计数
        function updateCommentCount(count) {
            commentCount.textContent = `${count} 条评论`;
        }
        
        // 转义HTML特殊字符，防止XSS攻击
        function escapeHtml(unsafe) {
            if (!unsafe) return '';
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }
        
        // 格式化评论内容（简单处理换行）
        function formatCommentContent(content) {
            return content.replace(/\n/g, '<br>');
        }
        
        // 主题切换功能（简单实现）
        function toggleTheme() {
            document.body.classList.toggle('bg-gray-900');
            document.body.classList.toggle('bg-gray-50');
            document.body.classList.toggle('text-white');
            document.body.classList.toggle('text-dark');
            
            
            const icon = themeToggle.querySelector('i');
            if (icon.classList.contains('fa-moon-o')) {
                icon.classList.replace('fa-moon-o', 'fa-sun-o');
            } else {
                icon.classList.replace('fa-sun-o', 'fa-moon-o');
            }
            
            showNotification('主题已切换', 'info');
        }
        
        // 暴露函数到全局，以便在HTML中调用
        window.replyTo = replyTo;
        window.deleteComment = deleteComment;
    </script>
</body>
</html>
    